package com.ckx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ckx.constants.SystemConstants;
import com.ckx.domain.entity.LoginUserDetails;
import com.ckx.domain.entity.User;
import com.ckx.mapper.UserMapper;
import com.ckx.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //根据用户名查询用户信息
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(User::getUserName, username);
        User user = userMapper.selectOne(wrapper);
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名错误");
        }

        //获取权限信息
        if (SystemConstants.ADMAIN.equals(user.getType())) {//管理员
            List<String> perms = menuService.selectPermsByUserId(user.getId());
            //返回带权信息
            return new LoginUserDetails(user, perms);
        }
        //返回信息
        return new LoginUserDetails(user, null);

    }
}
